package com.apache.portal.common.restfull;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.apache.portal.common.annotion.AnnotationUtil;
import com.apache.portal.common.annotion.BeanFactory;

public class ResultServletContainer implements ServletContainer {
	private String[] servletPackages;
	private Map<String, ResultFullServletSupper> servlets = new LinkedHashMap<String, ResultFullServletSupper>();

	public ResultServletContainer(String[] servletPackages) {
		this.servletPackages = servletPackages;
	}

	public ResultServletContainer() {

	}

	public void initContainer() {
		for (String servletPackage : servletPackages) {
			AnnotationUtil.getInstance().loadCalssBean(servletPackage);
		}
		servlets = BeanFactory.getInstance().getServlets();
	}

	public void initContainer(String[] className) {
	}

	public ResultFullServletSupper getServlet(String uri) {
		ResultFullServletSupper servletBean = servlets.get(uri);
		if (servletBean != null) {
			return servletBean;
		}
		for (String uriInMap : servlets.keySet()) {
			if (Pattern.matches(uriInMap, uri)) {
				return servlets.get(uriInMap);
			}
		}
		return null;
	}

	public String[] getParamsInUri(String uri) {
		ResultFullServletSupper servletBean = servlets.get(uri);
		if (servletBean != null) {
			return new String[] {};
		}
		for (String uriInMap : servlets.keySet()) {
			Pattern pattern = Pattern.compile(uriInMap);
			Matcher matcher = pattern.matcher(uri);

			String[] params = null;
			if (matcher.matches()) {
				int count = matcher.groupCount();
				params = new String[count];

				for (int i = 1; i <= count; i++) {
					params[i - 1] = matcher.group(i);
				}
				return params;
			}
		}
		return new String[] {};
	}

}
